package com.atguigu.gmall.common.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送消息
     * @param exchange
     * @param routingKey
     * @param msg
     * @return
     */
    public Boolean sendMsg(String exchange,String routingKey,Object msg){
        //  创建一个对象
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString().replace("-","");
        //  消息的唯一标识  key = spring_returned_message_correlation value = uuid
        //  spring_returned_message_correlation:uuid
        gmallCorrelationData.setId(uuid);
        gmallCorrelationData.setMessage(msg);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);

        //  记录到redis中！
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);

        //  调用工具类发送消息
        //  rabbitTemplate.convertAndSend(exchange,routingKey,msg);
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,gmallCorrelationData);
        //  默认返回true
        return true;
    }

    /**
     * 发送延迟消息.
     * @param exchange
     * @param routingKey
     * @param msg
     * @param delayTime
     * @return
     */
    public Boolean sendDelayMsg(String exchange,String routingKey,Object msg,int delayTime){
        //  需要将数据封装到
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString().replace("-","");
        //  消息的唯一标识  key = spring_returned_message_correlation value = uuid
        //  spring_returned_message_correlation:uuid
        gmallCorrelationData.setId(uuid);
        gmallCorrelationData.setMessage(msg);
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        //  延迟消息
        gmallCorrelationData.setDelay(true);
        //  设置延迟时间
        gmallCorrelationData.setDelayTime(delayTime);

        //  记录到redis中！
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);

        //  发送延迟消息
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,
                (message)->{
                    //  设置延迟时间：10s
                    message.getMessageProperties().setDelay(1000*delayTime);
                    return message;
                },gmallCorrelationData);
        //  默认返回
        return true;
    }
}
